package com.salon.client.widgets;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.KeyListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.util.Params;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.salon.client.GreetingServiceAsync;
import com.salon.client.InfoHelper;
import com.salon.client.Salon;

public class RegistrationDialog extends Dialog {
	  protected TextField<String> userName;
	  protected TextField<String> password;
	  protected TextField<String> confPassword;
	  protected TextField<String> email;
	  protected Button reset;
	  protected Button login;
	  protected Status status;
	  
	  public RegistrationDialog() {
		  FormLayout layout = new FormLayout();
		  layout.setLabelWidth(90);
		  layout.setDefaultWidth(155);
		  setLayout(layout);

		  setButtonAlign(HorizontalAlignment.LEFT);
		  setButtons("");
		  setIcon(IconHelper.createStyle("user"));
		  setHeading("Регистрация");
		  setBodyBorder(true);
		  setBodyStyle("padding: 8px;background: none");
		  setWidth(300);
		  setResizable(false);
		  KeyListener keyListener = new KeyListener() {
		   public void componentKeyUp(ComponentEvent event) {
		        if (validate()) {
		        	if (event.getKeyCode() == 13) {
		        		onSubmit();
		        	}
		        }
		   }
		 };
  
		 userName = new TextField<String>();
		 userName.setMinLength(4);
		 userName.setFieldLabel("Логин");
		 userName.addKeyListener(keyListener);
		 add(userName);

		 password = new TextField<String>();
		 password.setMinLength(4);
		 password.setPassword(true);
		 password.setFieldLabel("Пароль");
		 password.addKeyListener(keyListener);
		 add(password);
		 
		 confPassword = new TextField<String>();
		 confPassword.setMinLength(4);
		 confPassword.setPassword(true);
		 confPassword.setFieldLabel("Повторный пароль");
		 confPassword.addKeyListener(keyListener);
		 add(confPassword);
		 
		 email = new TextField<String>();
		 email.setMinLength(4);
		 email.setFieldLabel("Имя пользователя");
		 email.addKeyListener(keyListener);
		 add(email);

		 setFocusWidget(userName);
	  }
	  
	  @Override
	  protected void createButtons() {
		super.createButtons();
	    status = new Status();
	    status.setBusy("Идет загрузка...");
	    status.hide();
	    status.setAutoWidth(true);
	    getButtonBar().add(status);
	    
	    getButtonBar().add(new FillToolItem());
	    
	    reset = new Button("Сброс");
	    reset.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {
	        userName.reset();
	        password.reset();
	        confPassword.reset();
	        validate();
	        userName.focus();
	      }

	    });

	    login = new Button("OK");
	    login.disable();
	    login.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {
	        onSubmit();
	      }
	    });

	    addButton(reset);
	    addButton(login);
	  }
	  
	  protected void onSubmit() {
			if (!confPassword.getValue().equals(password.getValue())) {
				confPassword.forceInvalid("Required field");
				confPassword.focus();
				Info.display("Ошибка", 
						"<font color=red>Введенные пароли не совпадают</font>");
				return;
			}
			
		    status.show();
		    getButtonBar().disable();
	
		    ((GreetingServiceAsync) Registry.get(Salon.SERVICE)).
		    	register(userName.getValue(), password.getValue(), email.getValue(),
		    			new AsyncCallback<Void>() {
	
							@Override
							public void onFailure(Throwable caught) {
								Info.display("<font color=red>Ошибка регистрации</font>", caught.getMessage());
								status.hide();
								getButtonBar().enable();
								
							}
	
							@Override
							public void onSuccess(Void result) {
								Info.display(InfoHelper.getWarning("Регистрация проведена"), 
										InfoHelper.getWarning("Успешно"));
				
								RegistrationDialog.this.hide();
							}
		    		
		    	});
	  }
	  
	  protected boolean hasValue(TextField<String> field) {
		    return field.getValue() != null && field.getValue().length() > 0;
	  }

	  protected boolean validate() {
		boolean allFieldsHasValue = hasValue(userName) && hasValue(password) && hasValue(confPassword);
	    login.setEnabled(allFieldsHasValue);
	    return allFieldsHasValue;
	  }
	  
	  private boolean isValidMail() {
		  String emailString = email.getValue();
		  if (emailString == null) {
			  return false;
		  }
		  String[] partsemail = emailString.split("@");
		  if (partsemail.length < 2) {
			  return false;
		  }
		  if ((partsemail[0].length() > 0) && (partsemail[1].length() > 3)) {
			  String[] partsemail2 = partsemail[1].split("\\.");
			  if (partsemail2.length > 1) {
				  if ((partsemail2[0].length() > 0) &&
				  	  ((partsemail2[1].length() > 1))) {
					  email.clearInvalid();
					  return true;
				  }
			  }
		  }
		  return false;
	  }
}
